var models = require('../db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../sqlMap');

// 连接数据库
var conn = mysql.createConnection(models.mysql);

conn.connect();
var jsonWrite = function(res, ret) {
  if(typeof ret === 'undefined') {
    res.json({
      code: '1',
      msg: '操作失败'
    });
  } else {
    res.json(ret);
  }
};

// 增加用户接口
router.post('/addUser', (req, res) => {
  var sql = $sql.userAdd.user.add;
  var params = req.body;
  console.log(params);
  conn.query(sql, [params.username, params.age], function(err, result) {
    if (err) {
      console.log(err);
    }
    if (result) {
      jsonWrite(res, result);
    }
  })
});

// 增加注册用户接口
router.post('/register', (req, res) => {
  var sql = $sql.reg.register.add;
  var params = req.body;
  console.log(params);
  conn.query(sql, [params.username, params.password, params.cTime, params.nickname], function(err, result) {
    if (err) {
      jsonWrite(res, err)
    }
    if (result) {
      jsonWrite(res, result);
    }
  })
});

// 增加注册用户接口
router.post('/getAllUser', (req, res) => {
  req.query.size = req.query.size || 20;
  req.query.p = req.query.p || 0;
  var sql = $sql.userSelectAll.userSelectAll.select(req.query);
  //var params = req.body;
  conn.query(sql, [], function(err, result) {
    if (err) {
      console.log(err);
    }
    if (result) {
      jsonWrite(res, result);
    }
  })
});

// 获取登录用户信息
router.post('/getLoginInfo', (req, res) => {
  var sql = $sql.loginInfo.loginInfo.select;
  var params = req.body;
  console.log(params);
  conn.query(sql, [params.username], function(err, result) {
    if (err) {
      jsonWrite(res, err);
    }
    if (result) {
      jsonWrite(res, result);
    }
  })
});

module.exports = router;
